package org.ucas.kgraph.controller;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.session.HttpServletSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.ucas.kgraph.dto.ErrDto;
import org.ucas.kgraph.entity.Account;
import org.ucas.kgraph.entity.UserProfile;
import org.ucas.kgraph.service.UserService;
import org.ucas.kgraph.utils.constants.ErrCode;
import org.ucas.kgraph.utils.exception.ExceptionUtil;
import org.ucas.kgraph.utils.exception.RestException;
import org.ucas.kgraph.utils.security.UserPrincipal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 大部分Controller的基本父类,集成获取登陆用户、异常处理等基本功能
 *
 * @author suemi
 */
public abstract class BaseController {

  @Autowired
  UserService userService;

  @Autowired
  HttpSession session;

  protected Logger logger = Logger.getLogger(this.getClass());


  protected UserPrincipal principal() {
    return (UserPrincipal) SecurityUtils.getSubject().getPrincipal();
  }

  protected UserProfile profile() {
    UserPrincipal userPrincipal = principal();
    return userPrincipal == null ? null : userService.profile(userPrincipal.id).orElse(null);
  }

  protected Account current() {
    UserPrincipal userPrincipal = principal(); 
    return userPrincipal == null ? null : userService.load(userPrincipal.id).get();
  }

  protected Subject subject() {
    return SecurityUtils.getSubject();
  }

  protected boolean isLogin() {
    return subject().isAuthenticated();
  }

  protected Long root() {
    return (Long) session.getAttribute("root");
  }

  protected void root(Long rootId) {
    session.setAttribute("root", rootId);
  }
  
  protected Long selfroot() {
    return (Long) session.getAttribute("selfroot");
  }
  protected void selfroot(Long selfmlibId) {
    session.setAttribute("selfroot", selfmlibId);
  }
  
  protected Long searchroot() {
    return (Long) session.getAttribute("searchroot");
  }
  
  protected void searchroot(Long searchId) {
	session.setAttribute("searchroot", searchId);
  }
  protected Long file() {
	return (Long) session.getAttribute("file");
  }
	  
  protected void file(Long file) {
	session.setAttribute("file", file);
  }
  protected String code() {
	return session.getAttribute("code").toString();
  }  
  protected void code(String code) {
	session.setAttribute("code", code);
  }
  protected String telenumber() {
	return session.getAttribute("telenumber").toString();
  }  
  protected void telenumber(String telenumber) {
	session.setAttribute("telenumber", telenumber);
  }
  
}
